package com.example.myapplication;

import android.media.SoundPool;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.myapplication.adapters.SoundPoolAdapter;

import java.util.ArrayList;
import java.util.List;

public class SoundPoolActivity extends AppCompatActivity implements SoundPoolAdapter.OnItemClickListener {

    public static class Sound {
        private final String name;
        private final int soundId;

        public Sound(String name, int soundId) {
            this.name = name;
            this.soundId = soundId;
        }

        public String getName() {
            return name;
        }

        public int getSoundId() {
            return soundId;
        }
    }

    List<Sound> data;
    private SoundPool soundPool;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sound_pool);
        //获取recycler控件
        RecyclerView recyclerView = findViewById(R.id.recyc_sound);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayout.VERTICAL);
        //给控件设置布局
        recyclerView.setLayoutManager(linearLayoutManager);

        soundPool = new SoundPool.Builder().build();

        data = new ArrayList<>();
        data.add(new Sound("1", soundPool.load(this, R.raw.a1, 1)));
        data.add(new Sound("2", soundPool.load(this, R.raw.a2, 1)));
        data.add(new Sound("3", soundPool.load(this, R.raw.a3, 1)));
        data.add(new Sound("4", soundPool.load(this, R.raw.a4, 1)));

        SoundPoolAdapter soundPoolAdapter = new SoundPoolAdapter(data, this, recyclerView);
        soundPoolAdapter.setOnItemClickListener(this);
        recyclerView.setAdapter(soundPoolAdapter);

    }

    @Override
    public void onItemClick(int childAdapterPosition) {
        Toast.makeText(this, String.valueOf(childAdapterPosition), Toast.LENGTH_SHORT).show();
        Sound sound = data.get(childAdapterPosition);
        soundPool.play(sound.getSoundId(), 0.5f, 0.5f, 1, 0, 1.0f);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        for (Sound datum : data) {
            soundPool.unload(datum.getSoundId());
        }
        soundPool.release();
    }
}